package com.xxg.curd.impl;

import com.xxg.curd.CurdConfig;
import com.xxg.curd.ex.CurdException;

import java.util.HashMap;
import java.util.Map;

/**
 * SQL 映射关系
 */
public class SimpleSQLMap extends BaseSQLMapImpl {

    //类名对应的字段映射属性
    private Map<String,String> classMap = new HashMap<>();
    private Map<String,Map<String,String>> attributeMap = new HashMap<>();

    public SimpleSQLMap(CurdConfig config){
        super(config);
        rkv();
    }

    public void rkv(){
        tableMap.forEach((k,v) -> classMap.put(v,k));
        fieldMap.forEach((k,v) -> {
            HashMap<String, String> nMap = new HashMap<>(v);
            v.clear();
            nMap.forEach((a,f) -> v.put(f,a));
            attributeMap.put(k,nMap);
        });
    }

    public String getTableName(String tableName){
        String txt = tableMap.get(tableName);
        if(txt == null || txt.length() ==0 ){
            throw new CurdException("表不存在 tableName = " + tableName);
        }
        return txt;
    }

    public String getFieldName(String tableName,String fieldName){
        Map<String, String> map = fieldMap.get(tableName);
        if(null != map){
            String text = map.get(fieldName);
            if(text == null || text.length() ==0 ) {
                throw new CurdException(String.format("字段不存在 tableName = %s; fieldName = %s",tableName,fieldName));
            }
            return text;
        }else {
            throw new CurdException("表不存在 tableName = " + tableName);
        }
    }

    @Override
    public String getClassName(String className) {
        String txt = classMap.get(className);
        if(txt != null && txt.length() !=0 )return txt;
        return className;
    }

    @Override
    public String getAttributeName(String className, String attributeName) {
        Map<String, String> map = attributeMap.get(className);
        if(null != map){
            String text = map.get(attributeName);
            if(text != null && text.length() !=0 )return text;
        }
        return attributeName;
    }
}
